require('./jquery.datetimePicker.core.js');

function datetimePicker() {
    return {
        restrict: "EA",
        require: "ngModel",
        scope: {
            model: '=ngModel'
        },
        css: require('./jquery.datetimePicker.css'),
        link: function(scope, element, attrs, ctrl) {
            var unregister = scope.$watch(function() {
                $(element).append("<input id='date-" + attrs.dateid + "' style='border:none; width:100%; height:100%; outline:none;' " + "value='" + (!!ctrl.$modelValue ? ctrl.$modelValue : "") + "'>");
                $(element).find('input').css('outline', 'none');

                ctrl.$render = function() {
                    if (typeof scope.model !== undefined)
                        $("#date-" + attrs.dateid).val(scope.model);
                };

                $(element).on('change', function() {
                    scope.$apply(function() {
                        var datetime = $("#date-" + attrs.dateid).val();
                        if (!datetime) {
                            var d = new Date();
                            datetime = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
                        }
                        ctrl.$setViewValue(datetime);
                    });
                });

                element.on('click', function() {
                    var d = new Date();
                    var maxday = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
                    var minday = (d.getFullYear() - 100) + "-1-1";
                    var step = 1;
                    $("#date-" + attrs.dateid).datetimepicker({
                        format: attrs.format || 'Y-m-d H:i',
                        timepicker: attrs.timepicker == "false" ? false : true,
                        minDate: !!attrs.mindate ? attrs.mindate : minday,
                        maxDate: !!attrs.maxdate ? attrs.maxdate : maxday,
                        step: !!attrs.step ? attrs.step : step,
                        onClose: function() {
                            $(element).change();
                        }
                    });
                });


                $(element).click();

                return !!ctrl.$modelValue ? ctrl.$modelValue : "";
            }, initialize);

            function initialize(value) {
                ctrl.$setViewValue(!!value ? value : "");
                unregister();
            }
        }
    }
}

module.exports = datetimePicker;
